import request from '@/utils/request'

// get
export function getAction (url, parameter) {
  return request({
    url: url,
    method: 'get',
    params: parameter
  })
}
export function uploadAction(url, formData, callback) {
  return request({
    url,
    method: 'post',
    transformRequest: [function(data, headers) {
      delete headers['Content-Type']
      return data
    }],
    data: formData,
    onUploadProgress: progressEvent => {
      callback && callback( progressEvent.loaded / progressEvent.total * 100 | 0)
    }
  })
}
// post
export function postAction (url, parameter) {
  return request({
    url: url,
    method: 'post',
    data: parameter
  })
}

// post
export function postActionPa (url, parameter) {
  return request({
    url: url,
    method: 'post',
    params: parameter
  })
}
// 下载文件
export function downFile (url, parameter) {
  return request({
    url: url,
    params: parameter,
    method: 'get',
    responseType: 'blob'
  })
}

// deleteAction
export function deleteAction (url, parameter) {
  return request({
    url: url,
    method: 'delete',
    params: parameter
  })
}

// 通用文件下载方法
export function downloadFile(url, parameter, fileName) {
  return request({
    url: url,
    method: 'get',
    params: parameter,
    responseType: 'blob'
  }).then(res => {
    // 创建 blob
    const blob = new Blob([res], {
      type: 'application/octet-stream;charset=UTF-8'
    })
    
    // 如果没有传入文件名，尝试从响应头获取
    if (!fileName) {
      const contentDisposition = res.headers?.['content-disposition']
      if (contentDisposition) {
        fileName = contentDisposition.split('filename=')[1]
      } else {
        fileName = '下载文件.xlsx'
      }
    }

    if (window.navigator.msSaveOrOpenBlob) {
      // IE10+
      window.navigator.msSaveOrOpenBlob(blob, fileName)
    } else {
      // 非IE
      const link = document.createElement('a')
      const url = window.URL.createObjectURL(blob)
      link.href = url
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    }
    return Promise.resolve()
  }).catch(error => {
    console.error('下载失败:', error)
    return Promise.reject(error)
  })
}

